package com.tiantian.framework.handler;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 类型转换器，用于数据库的BINGINT和Java中List<Long>类型的相互转换
 *
 * @author TianTian
 */
@MappedJdbcTypes(JdbcType.BINARY)
@MappedTypes(List.class)
public class ListToLongTypeHandler implements TypeHandler<List<Long>> {
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, List<Long> longs, JdbcType jdbcType) throws SQLException {
        // 遍历List类型的入参，拼装为Long类型，使用Statement对象插入数据库
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < longs.size(); j++) {
            if (j == longs.size() - 1) {
                sb.append(longs.get(j));
            } else {
                sb.append(longs.get(j)).append(",");
            }
        }
        preparedStatement.setString(i, sb.toString());
    }

    @Override
    public List<Long> getResult(ResultSet resultSet, String s) throws SQLException {
        // 获取Long类型的结果，使用","分割为List后返回
        String resultString = resultSet.getString(s);
        return getLongs(resultString);
    }

    @Override
    public List<Long> getResult(ResultSet resultSet, int i) throws SQLException {
        // 获取Long类型的结果，使用","分割为List后返回
        String resultString = resultSet.getString(i);
        return getLongs(resultString);
    }

    @Override
    public List<Long> getResult(CallableStatement callableStatement, int i) throws SQLException {
        // 获取String类型的结果，使用","分割为List后返回
        String resultString = callableStatement.getString(i);
        return getLongs(resultString);
    }

    private static List<Long> getLongs(String resultString) {
        if (StringUtils.isNotEmpty(resultString)) {
            String[] list = resultString.split(",");
            List<Long> res = new ArrayList<>();
            for (String s1 : list) {
                res.add(Long.valueOf(s1));
            }
            return res;
        }
        return new ArrayList<>();
    }

}
